package com.sztu.controller;

import com.sztu.pojo.User;
import com.sztu.service.UserServiceImpl;
import com.sztu.token.JwtToken;
import com.sztu.token.LoginType;
import com.sztu.utils.JwtUtil;
import com.sztu.utils.Result;
import io.jsonwebtoken.Claims;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.oas.annotations.EnableOpenApi;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.LinkedHashMap;
import java.util.Map;

@EnableOpenApi
@RestController
public class LoginController {
    @Autowired
    UserServiceImpl userService;

    @RequestMapping("/verifyToken")
    public Result verifyToken(ServletRequest servletRequest){
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        String jwt=null;
        Claims claims = null;
        try {
            jwt=request.getHeader("Authorization");
            claims= (Claims) JwtUtil.parseToken(jwt);
        }catch (Exception e){
            return new Result().setCode(401).setMessage("未登录，请登录");
        }
        return new Result().setCode(200).setMessage("token有效").setData(new User().setName(claims.getId()));
    }


    @PostMapping("/userLogin")
    public Result shiroLogin(@RequestBody User requestUser){
        Subject subject= SecurityUtils.getSubject();
        String jwt=JwtUtil.createToken(requestUser.getName(),"back","user");
        JwtToken token=new JwtToken(jwt,requestUser.getPwd());
        token.setLoginType(LoginType.SHIRO_USER);
        try {
            subject.login(token);
        }catch (UnknownAccountException e){
            return new Result().setCode(401).setMessage("用户不存在");
        }catch (IncorrectCredentialsException e){

            return new Result().setCode(401).setMessage("密码错误");
        }
        try{
            subject.checkPermission("*");
        }catch (Exception e){
            // doNothing
        }

        Map principal = (Map) subject.getPrincipal();
        // 登录成功
        requestUser.setPwd(null);
        Map<String,Object> data=new LinkedHashMap<>();
        data.put("token",jwt);
        data.put("user",principal);
        return new Result().setCode(200).setMessage("登录成功").setData(data);
    }
}
